package collection;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author jiangwz
 * @create 2019/9/28.
 */
public class LRUCache<K, V> extends LinkedHashMap<K, V> {

    private static final int MAX_NUM = 100;

    private int limit;

    public LRUCache() {
        this(MAX_NUM);
    }

    public LRUCache(int limit) {
        super(limit, 0.75f, true);
        this.limit = limit;
    }

    public V save(K k, V v) {
        return put(k, v);
    }

    public V getOne(K k){
        V v = get(k);
        return v;
    }

    public boolean exits(K k){
        return containsKey(k);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > limit;
    }

    public static void main(String[] args){
        LRUCache<Integer, Integer> cache = new LRUCache<>(3);
//        test01(cache);

        cache.put(1, 1);
        cache.put(2, 2);
        cache.put(3, 3);
        System.out.println(cache);
        cache.put(1, 1);
        System.out.println(cache);


    }

    private static void test01(LRUCache<Integer, Integer> cache) {
        for (int i = 0; i < 10; i++) {
            cache.save(i, i * i);
        }

        System.out.println("插入10个键值对后，缓存内容：");
        System.out.println(cache + "\n");

        System.out.println("访问键值为7的节点后，缓存内容：");
        cache.getOne(7);
        System.out.println(cache + "\n");

        System.out.println("插入键值为1的键值对后，缓存内容：");
        cache.save(1, 1);
        System.out.println(cache);

        System.out.println(cache.getOne(2));
        System.out.println(cache);
    }
}
